package com.woniu.cloud.marketingassembly.apiImpl;

import com.woniu.cloud.api.MarketingApi;
import com.woniu.cloud.common.dto.Result;
import com.woniu.cloud.form.CouponForm;
import com.woniu.cloud.entity.TCoupon;
import com.woniu.cloud.marketingassembly.service.ITCouponService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@Slf4j
public class MarketingApiImpl implements MarketingApi {

    @Resource
    private ITCouponService couponService;

    @Override
    @GetMapping("getCouponByConponId")
    @GlobalTransactional
    public Result getCouponByConponId(Integer conponId) {
        log.info("通过优惠券id查找->conponId:{}",conponId);
        if (null==conponId) {
            return Result.fail("参数异常",null);
        }
        try {
            log.info("开始查询->conponId:{}",conponId);
            return couponService.getCouponByConponId(conponId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("异常",null);
        }
    }

    @Override
    @PostMapping("insertCoupon")
    @GlobalTransactional
    public Result insertCoupon(@RequestBody CouponForm couponForm) {
        log.info("添加优惠券->couponForm:{}",couponForm);
        if (null==couponForm) {
            return Result.fail("参数异常",null);
        }
        try {
            TCoupon coupon = new TCoupon();
            BeanUtils.copyProperties(couponForm,coupon);
            log.info("开始添加->coupon:{}",coupon);
            return couponService.insertCoupon(coupon);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("查询失败",null);
        }
    }

    @Override
    public Result getCouponByPrice(Double price) {
        TCoupon tCoupon = couponService.getCouponByPrice(price);
        return Result.success("查询成功",tCoupon);
    }

    @Override
    @DeleteMapping("deleteCouponByConponId")
    @GlobalTransactional
    public Result deleteCouponByConponId( Integer conponId) {
        log.info("通过优惠券id删除->conponId:{}",conponId);
        if (null==conponId) {
            return Result.fail("参数异常",null);
        }
        try {
            log.info("开始删除->conponId:{}",conponId);
            return couponService.deleteCouponByConponId(conponId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("异常",null);
        }
    }
}
